import datetime
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from django.db.models import Sum
from .models import ReadNum, ReadDetail


# 封装判断计数的方法
def read_statistics_once_read(request, obj):
	ct = ContentType.objects.get_for_model(obj)
	key = '%s_%s_read' % (ct.model, obj.pk)

	if not request.COOKIES.get(key):
		# if ReadNum.objects.filter(content_type=ct, object_id=obj.pk).count():
		# 	# 存在记录
		# 	readnum = ReadNum.objects.get(content_type=ct, object_id=obj.pk)
		# else:
		# 	# 不存在对应的记录
		# 	readnum = ReadNum(content_type=ct, object_id=obj.pk)

		# 查询总阅读数记录，没有则创建(get_or_create)
		readnum, created = ReadNum.objects.get_or_create(content_type=ct, object_id=obj.pk)
		# 计数加1
		readnum.read_num += 1
		readnum.save()

		# 当天阅读数 +1
		date = timezone.now().date()
		readDetail, created = ReadDetail.objects.get_or_create(content_type=ct, object_id=obj.pk, date=date)
		readDetail.read_num += 1
		readDetail.save()
	return key


def get_seven_days_read_data(content_type):
	today = timezone.now().date()
	dates = []
	read_nums = []
	for i in range(7, 0, -1):
		date = today - datetime.timedelta(days=i)
		dates.append(date.strftime('%m/%d'))
		read_details = ReadDetail.objects.filter(content_type=content_type, date=date)
		result = read_details.aggregate(read_num_sum=Sum('read_num'))
		read_nums.append(result['read_num_sum'] or 0)
	return dates, read_nums


# 获取今天热门阅读的博客数据统计
def get_today_hot_data(content_type):
	today = timezone.now().date()
	read_details = ReadDetail.objects.filter(content_type=content_type, date=today).order_by('-read_num')
	# 取前7条数据
	return read_details[:7]


	# 获取昨天热门阅读的博客数据统计
def get_yesterday_hot_data(content_type):
	 today = timezone.now().date()
	 yesterday = today - datetime.timedelta(days=1)
	 read_details = ReadDetail.objects.filter(content_type=content_type, date=yesterday).order_by('-read_num')
	 # 取前7条数据
	 return read_details[:7]




